package com.effect.exception;
import com.effect.controller.BaseController;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;


@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {

	@ResponseBody
	@ExceptionHandler({MissingServletRequestParameterException.class, MethodArgumentNotValidException.class, BindException.class})
	public ResultSetBO globalParamException(Exception e) {
		log.error("{}:{}", ResultCode.PARAM_ERROR.getValue(), e);
		return fail(ResultCode.PARAM_ERROR,e.getMessage());
	}
	

	@ResponseBody
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public ResultSetBO globalException(HttpRequestMethodNotSupportedException e) {
		log.error("请求方式错误 :{}", e);
		return fail(ResultCode.REQUEST_METHOD_ERROR, e.getMessage());
	}

	@ResponseBody
	@ExceptionHandler(CustomizeException.class)
	public ResultSetBO globalException(CustomizeException e) {
		log.error("自定义异常 CustomException：{}", e.getMessage());
		return fail(e.getCode(), e.getMessage(), null);
	}
	

	@ResponseBody
	@ExceptionHandler(NullPointerException.class)
	public ResultSetBO globalException(NullPointerException e) {
		log.error("NullPointerException 异常：{}", e);
		return fail(ResultCode.NULL_Pointer_ERROR, e);
	}

	@ResponseBody
	@ExceptionHandler(RuntimeException.class)
	public ResultSetBO globalException(RuntimeException e) {

		if (e instanceof ResourceAccessException) {
			log.error("服务拒绝连接或请求异常:{}" ,e);
			return fail(null, "服务拒绝连接或请求异常,检查服务是否启动 ", "错误信息: " + e);
		}
		if (e instanceof HttpClientErrorException) {
			log.error("服务请求403错误信息:{}" ,e);
			return fail(null, "服务请求403，检查请求接口路径是否正确", "错误信息:" + e);
		}
		log.error("运行时异常:{}" ,e);
		return fail(null, ResultCode.SYSTEM_ERROR.getValue(), null);
	}

	@ResponseBody
	@ExceptionHandler(Exception.class)
	public ResultSetBO globalException(Exception e) {
        log.error(e.getMessage(), e);
		return fail(null, ResultCode.SYSTEM_ERROR.getValue(), e);
	}

	@ExceptionHandler(BizException.class)
	public ResultSetBO globalException(BizException e) {
		log.error(e.getMessage(), e);
		return fail(e.getCode(), e.getMessage(), null);
	}
}
